/*
	VerbCaptureShip.cpp
	(c)2000 Palestar Inc, Richard Lyle
*/


#include "Debug/Assert.h"
#include "Math/Helpers.h"
#include "NounUnit.h"
#include "Resource.h"
#include "VerbCaptureShip.h"
#include "VerbUnload.h"
#include "GameContext.h"

//-------------------------------------------------------------------------------

IMPLEMENT_FACTORY( VerbCaptureShip, Verb );

BEGIN_PROPERTY_LIST( VerbCaptureShip, Verb )
	ADD_TRANSMIT_PROPERTY( m_nFleetId );
	ADD_TRANSMIT_PROPERTY( m_pWho );
END_PROPERTY_LIST();

VerbCaptureShip::VerbCaptureShip()
{}

VerbCaptureShip::VerbCaptureShip( NounShip * pShip, int teamId, Noun * pWho ) 
	: m_nFleetId( teamId ), m_pWho( pWho )
{
	attachVerb( pShip );
}

//----------------------------------------------------------------------------

Verb::Priority VerbCaptureShip::priority() const
{
	return MEDIUM;
}

Verb::Scope VerbCaptureShip::scope() const
{
	return LOCAL;
}

bool VerbCaptureShip::client() const
{
	return false;
}

bool VerbCaptureShip::canAttach( Noun * pNoun )
{
	return WidgetCast<NounShip>( pNoun ) != NULL;
}

void VerbCaptureShip::onExecute()
{
	NounShip * pShip = WidgetCast<NounShip>( target() );
	if ( validate( pShip ) )
	{
		Noun * pCapper = m_pWho;
		if ( WidgetCast<NounUnit>( pCapper ) )
			pCapper = ((NounUnit *)pCapper)->home();

		// inform user before we modify the ship
		((GameContext *)context())->gameUser()->onCaptureShip( pCapper, pShip );

		// ship captured set the owner
		pShip->setTeamId( m_nFleetId );
		pShip->setRank( 255 );								// don't allow anyone to order the ship
		pShip->setOrder( NounShip::NOORDER, NULL, pShip );	// set the ship to go home
		pShip->setUserId( 0 );								// disown the ship, so it's doesn't get stored

		// if we're the server, take control of this ship
		if ( context()->server() )
		{
			// jettison all cargo
			for(int i=pShip->childCount()-1;i>=0;i--)
			{
				NounGame * pChild = WidgetCast<NounGame>( pShip->child( i ) );
				if ( pChild != NULL && pChild->isCargo() )
					Verb::Ref( new VerbUnload( pShip, pShip, pChild ) );
			}
		}
	}
}

//----------------------------------------------------------------------------
//EOF
